package com.eol.service.sms;

import com.alibaba.fastjson.JSONObject;
import com.eol.common.constants.BaseCommonConstants;
import com.eol.common.constants.SMSConstants;
import com.eol.common.sequence.Sequence;
import com.eol.common.sms.SMSDto;
import com.eol.common.sms.SMSUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * SmsService
 *
 * @author liulinhui
 * @email 1249055292@qq.com
 * @date 2020/6/1 21:28
 */
@Service
public class SmsService {

    @Resource
    private Sequence sequence;
    @Resource
    private SMSUtils smsUtils;
    @Value("${spring.profiles.active:'prod'}")
    private String profiles;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone 手机号码
     * @return uuid
     */
    public String sendVerifyCode(String phone) {
        String uuid = sequence.nextString();
        String code = "666666";
        JSONObject jsonObject = new JSONObject();
        if (profiles.contains(BaseCommonConstants.PROD)) {
            code = String.valueOf((int) ((Math.random() * 6 + 1) * 100000));
            //测试账号15189707662默认验证码666666
            if ("15189707662".contains(phone)) code = "666666";
            jsonObject.put("code", code);
            jsonObject.put("product", "");
            smsUtils.send(SMSDto.builder()
                    .phoneNum(phone)
                    .templateCode(SMSConstants.VERY_CODE_TEMPLATE.getTemplate())
                    .templateParam(jsonObject.toJSONString())
                    .build());
        }
        redisTemplate.opsForValue().set(uuid, code, 15, TimeUnit.MINUTES);
        return uuid;
    }
}
